package threecard.android.httpHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

/**
 * 
 * @author loandt
 *
 *Help to: Register, login, change account info, forgot password
 *
 *TASK:
 *
 *1. REGISTER: 
  	AccountDbHelper account = new AccountDbHelper();
 	account.actionRegister(String username,String password,String email);
 *
 *2. LOGIN:
 	AccountDbHelper account = new AccountDbHelper(String username,String password);
 	boolean result = account.actionLogin();
 *
 *3. CHANGE EMAIL
 	AccountDbHelper account = new AccountDbHelper(String username,String password);
 	boolean result = account.actionChangeEmail(String email);
 *
 *4. CHANGE PASSWORD:
	AccountDbHelper account = new AccountDbHelper(String usernam,String password);
 	boolean result = account.actionChangePassword(String newPassword);
 *
 * 5. FORGOT PASSWORD
  	AccoutnDbHelper account = new AccountDbHelper(String username,null,String email);
  	boolean resul = account.actionForgotPassword();
 */
public class AccountDbHelper  {
	public static final int ACTION_REGISTER = 0;
	public static final int ACTION_LOGIN = 1;
	public static final int ACTION_SET_PASSWORD = 2;
	public static final int ACTION_SET_EMAIL = 3;
	public static final int ACTION_FORGOT_PASSWORD = 4;
	protected String mUsername;
	protected String mPassword;
	protected String mEmail;
	protected String token;
	public AccountDbHelper(){
		mUsername = null;
		mPassword = null;
	}
	/**
	 * CONSTRUCTOR: Create an AccountDbHelper from provided username and password
	 * @param username - String
	 * @param password - String md5
	 */
	public AccountDbHelper(String username,String password){
		mUsername = username;
		mPassword =  password;
	}
	/**
	 * Create an AccountDbHelper from provided username
	 * @param username
	 */
	public AccountDbHelper(String username,String password,String email){
		mUsername = username;
		mEmail = email;
	}
	public void setUsername(String username){
		mUsername = username;
	}
	public String getUsername(){
		return mUsername;
	}
	public void setPassword(String password){
		mPassword =  password;
	}
	public String getPassword(){
		return mPassword;
	}
	/**
	 * REGISTER FOR NEW USER
	 * @param username: String
	 * @param password: String md5
	 * @param email: String
	 * @return: result of registetration: false or true
	 */
	public boolean actionRegister(String username,String password,String email){
		return  postData(ACTION_REGISTER, username, password,email,null) ;
	}
	/**
	 * LOGIN INTO SYSTEM
	 * @return: result of logining: true or false
	 */
	public String actionLogin(){
		if( postData(ACTION_LOGIN, mUsername,  mPassword, null, null) == true) return token;
		return "FAILED";
	}
	/**
	 * CHANGE NEW EMAIL
	 * @param email: String
	 * @return result of changing: true or false
	 */
	public boolean actionChangeEmail(String email){
		return  postData(ACTION_SET_EMAIL, mUsername,  mPassword,email,null);
	}
	/**
	 * CHANGE PASSWORD
	 * @param newPassword
	 * @return true or false == successful or failure
	 */
	public boolean actionChangePassword(String newPassword){
		return postData(ACTION_SET_PASSWORD, mUsername,  mPassword,null, newPassword) ;
	}
	public boolean actionForgotPassword(){
		return postData(ACTION_FORGOT_PASSWORD, mUsername,  null,mEmail,null);
	}
	
	/**
	 * POST DATA TO SERVER
	 * @param task - integer: type of task to do: register, login, change email or password
	 * @param username - String
	 * @param password - String md5
	 * @param newEmail - String 
	 * @param newPassword - String
	 * @return: result of action: true or false
	 */
		public boolean postData(int task,String username, String password,String newEmail,String newPassword) {
			String response = null;
			switch(task){
			case ACTION_REGISTER:
				ArrayList<NameValuePair> registerValues = new ArrayList<NameValuePair>();
				registerValues.add(new BasicNameValuePair("task","register"));
				registerValues.add(new BasicNameValuePair("regUsername",username));
				registerValues.add(new BasicNameValuePair("regPassword",password));
				registerValues.add(new BasicNameValuePair("regEmail",newEmail));
			    
			    // 1) Connect via HTTP. 2) Encode data. 3) Send data.
			    response = null;
				try {  
					response = CustomHttpClient.executeHttpPost("http://10.0.2.2/3cards/register.php", registerValues);  //Enetr Your remote PHP,ASP, Servlet file link
					String res = response.toString();
					res = res.replaceAll("\\s+","");
					if(res.contains("__successful__")){
						return true; //duplicate username or email
					}else{
						return false;
					}
				} catch (Exception e) {  
					e.printStackTrace();
				}
				break;
			case ACTION_LOGIN:
				//Add data to be send.
				
			    ArrayList<NameValuePair> loginValues = new ArrayList<NameValuePair>();
			    loginValues.add(new BasicNameValuePair("task","login"));
			    loginValues.add(new BasicNameValuePair("username",username));
			    loginValues.add(new BasicNameValuePair("password",password));
			    Log.i("set data","ok");
			     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
			    response = null;
				try {  
						response = CustomHttpClient.executeHttpPost("http://10.0.2.2/3cards/login.php", loginValues);  //Enetr Your remote PHP,ASP, Servlet file link
						String res = response.toString();  
						token ="";
						res = res.replaceAll("\\s+",""); 
						
						if(res.contains("__successful__")) {
							StringTokenizer st = new StringTokenizer(res, "__");
							String fst = st.nextToken();
							token = st.nextToken();
							return true;
						}else{  
							return false;
						}
				} catch (Exception e) { 
						
						Log.e("Login Exception", e.getMessage());
				}	
				break;
			case ACTION_SET_PASSWORD:
				//Add data to be send.
			    ArrayList<NameValuePair> setPwdValues = new ArrayList<NameValuePair>();
			    setPwdValues.add(new BasicNameValuePair("task","reset_password"));
			    setPwdValues.add(new BasicNameValuePair("username",username));
			    setPwdValues.add(new BasicNameValuePair("password",password));
			    setPwdValues.add(new BasicNameValuePair("newPassword",newPassword));
			    Log.i("set data","ok");
			     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
			    response = null;
				try {  
						response = CustomHttpClient.executeHttpPost("http://10.0.2.2/3cards/settings.php", setPwdValues);  //Enetr Your remote PHP,ASP, Servlet file link
						String res = response.toString();  
						
						res = res.replaceAll("\\s+","");  
						
						if(res.contains("__successful__")) {
							return true;
						}else{  
							return false;
						}
				} catch (Exception e) { 
						
						Log.e("Login Exception", e.getMessage());
				}	
				break;
			case ACTION_SET_EMAIL:
				//Add data to be send.
			    ArrayList<NameValuePair> setEmailValues = new ArrayList<NameValuePair>();
			    setEmailValues.add(new BasicNameValuePair("task","reset_email"));
			    setEmailValues.add(new BasicNameValuePair("username",username));
			    setEmailValues.add(new BasicNameValuePair("password",password));
			    setEmailValues.add(new BasicNameValuePair("newEmail",newEmail));
			    Log.i("set data","ok");
			     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
			    response = null;
				try {  
						response = CustomHttpClient.executeHttpPost("http://10.0.2.2/3cards/settings.php", setEmailValues);  //Enetr Your remote PHP,ASP, Servlet file link
						String res = response.toString();  
						
						res = res.replaceAll("\\s+","");  
						
						if(res.contains("__successful__")) {
							return true;
						}else{  
							return false;
						}
				} catch (Exception e) { 
						
						Log.e("Login Exception", e.getMessage());
				}	
				break;
			case ACTION_FORGOT_PASSWORD:
				//Add data to be send.
			    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			    nameValuePairs.add(new BasicNameValuePair("username",mUsername));
			    nameValuePairs.add(new BasicNameValuePair("email",mEmail));
			    Log.i("set data","ok");
			     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
				 response = null;
				try {  
						response = CustomHttpClient.executeHttpPost("http://10.0.2.2/3cards/resetpass.php", nameValuePairs);  //Enetr Your remote PHP,ASP, Servlet file link
						String res = response.toString();  
						
						res = res.replaceAll("\\s+","");  
						
						if(res.equals("e10adc3949ba59abbe56e057f20f883e")) {
							//createDialog("Success","Your password new is 123456, please change after login"); 
							return true;
						}else{  
							return false;
						}
				} catch (Exception e) {  
						e.printStackTrace();
				}
			default:
				break;
			}
			
			return false;
		}

		/**
		 * READ FROM RESPONSE TO STRING
		 * @param inputStream
		 * @return string s that is the response of action from server
		 * @throws IOException
		 */
		public String inputStreamToString(InputStream inputStream) throws IOException {
		    String s = "";
		    String line = "";
		    
		    // Wrap a BufferedReader around the InputStream
		    BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
		    
		    // Read response until the end
		    while ((line = rd.readLine()) != null) { s += line; }
		    
		    // Return full string
		    return s;
		}
}
